﻿using Treca.PushMessage.Business;
using Treca.Util;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Treca.PushMessage.Base.Base
{
    public static class PushMessageHelper
    {
        public static AjaxResult PushMessagePonit(WeiXinApp weiXinApp,string pointcode,string pointname)
        {
            try
            {
                IPMServiceContainer pMServiceContainer = AutofacHelper.GetScopeService<IPMServiceContainer>();
                Ims_messagepointconfigBusiness _MessagepointconfigBusiness = AutofacHelper.GetScopeService<Ims_messagepointconfigBusiness>();
                var msgconfig = _MessagepointconfigBusiness.GetIQueryable().Where(t => t.pointcode == pointcode && t.StatusFlag == "1").FirstOrDefault();
                if (msgconfig.IsNullOrEmpty())
                {
                    msgconfig = new Entity.ms_messagepointconfig();
                    msgconfig.Id = IdHelper.GetId();
                    msgconfig.ispush = "1";
                    msgconfig.pointcode = pointcode;
                    msgconfig.pointname = pointname;
                    msgconfig.appid = weiXinApp.appid;
                    msgconfig.wxappid = weiXinApp.wxappid;
                    msgconfig.pagepath = weiXinApp.pagepath;
                    msgconfig.templeteId = weiXinApp.templeteId;
                    _MessagepointconfigBusiness.AddData(msgconfig);
                    _MessagepointconfigBusiness.ApproveData(new List<string>() { msgconfig.Id });
                    pMServiceContainer.PushMessage(weiXinApp);
                }
                else
                {
                    if (msgconfig.ispush == "1")
                    {
                        weiXinApp.appid = msgconfig.appid;
                        weiXinApp.wxappid = msgconfig.wxappid;
                        weiXinApp.pagepath = msgconfig.pagepath;
                        weiXinApp.templeteId = msgconfig.templeteId;
                        pMServiceContainer.PushMessage(weiXinApp);
                    }
                }
            }catch(Exception ex)
            {
                LogHelper.WriteLog_LocalTxt("消息推送失败" + weiXinApp.ToJson() + ExceptionHelper.GetExceptionAllMsg(ex));
            }
            return AjaxHelper.Success(); ;
        } 
    }
}
